
package api;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Iterator;

import javax.swing.*;

import api.actions.Abrir;
import api.actions.Guardar;
import api.actions.Inicializar;
import api.actions.ManualObs;
import api.actions.RandomObs;

import busqueda.Busqueda;
import busqueda.Busqueda_Anchura;
import tablero.Tablero;
import tools.image.CargarIcono;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.MatteBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.LayoutStyle.ComponentPlacement;


public class Interface implements ActionListener {
	public static JFrame frame = new JFrame();
	public static JMenu smnObs;
	public static JMenu mnIni;
    public static JMenuItem mniInicializar;
	public JMenuItem acerca;
	public JMenuItem salir;
    public static Tablero Tab = new Tablero();
    public JPanel panelmeta;
    static int progreso;
    JDialog dialogo;
    JButton cancelar, aceptar;
    public static JButton btnStart;
    public static JMenuItem mnGuardarTablero;
    public static JFileChooser FileChooser;
    public static JMenuItem mnAbrir;
    public static int opcion;
    public static JMenuItem mnBusqueda;
    public static JMenu mnibusAstar;
    public static JLabel lblNombreBoH;
    
    private JLabel lblTablero;
    private JLabel lblLeyenda;
    private JPanel panelrobot;
    private JLabel lblPosirobo;
    private JPanel panelobs;
    private JLabel lblObstaculo;
    private JLabel lblPosicionFinal;
    private JLabel imgrobot;
    private JLabel imgobs;
    public JLabel imgfinal;
    public static JButton[][] panelTablero;
    private static JPanel panelTab;
    private static JDesktopPane desktopPane;
    public static JMenu mnEstrategiasaciegas;
    private static JMenu mnEstrategiasHeuristicas;
    public static int tipoHeuristica = 0;
    private JMenuItem mntmHeuristicaCityblock;
    private JMenuItem mntmHeuristicaEuclidiana;
    private JMenuItem mntmHeuristicaDiagonal;
    private JMenuItem mntmHeuristicaMaha;
    
    
	public Interface() {
		FileChooser = new JFileChooser();
		FileChooser.setAcceptAllFileFilterUsed(false);
		FileChooser.setFileFilter(new FileNameExtensionFilter("Archivos IA","ia"));
		
		frame.getContentPane().setBackground(Color.DARK_GRAY);
		frame.setTitle("Practica: Estrategias de busquedas.");
		
		frame.setBackground(Color.darkGray);
		
		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);

		JMenu mnIA = new JMenu("IA");
		mnIni = new JMenu("Inicializar");
		
	    menuBar.add(mnIA);
		menuBar.add(mnIni);
		
		acerca = new JMenuItem("Acerca de IA                  ");
		salir = new JMenuItem("Salir");
	    
	    salir.addActionListener(this);
	    acerca.addActionListener(this);

	    mnIA.add(acerca);
	    mnIA.add(new JSeparator());
	    mnIA.add(salir);	     	 
	    
	    cancelar = new JButton("Cancelar");
	    cancelar.addActionListener(this);
	    aceptar = new JButton("Aceptar");
	    aceptar.addActionListener(this);
		
	    mniInicializar = new JMenuItem("Inicializar tablero           ");
	    mniInicializar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Inicializar.run();
				
			}
		});
		
		mnAbrir = new JMenuItem("Abrir archivo  de tablero");
		mnIni.add(mnAbrir);
		
		mnAbrir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					Abrir.run();
					mnAbrir.setEnabled(false);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		JSeparator separator_2 = new JSeparator();
		mnIni.add(separator_2);
		mnIni.add(mniInicializar);
		
		mnIni.add(new JSeparator());
		
		smnObs = new JMenu("Inicializar obstaculos");
		
		JMenuItem randomObs = new JMenuItem("Obstaculos aleatorios");
		randomObs.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				RandomObs.run();
				mnAbrir.setEnabled(false);
			}
		});
		
		JMenuItem manualObs = new JMenuItem("Obstaculos manuales");
		manualObs.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ManualObs.run();
			}
		});
		
		smnObs.add(randomObs);
		smnObs.add(manualObs);
		
		mnIni.add(smnObs);
		
		smnObs.setEnabled(false);
		
		JSeparator separator_1 = new JSeparator();
		mnIni.add(separator_1);
		
		mnGuardarTablero = new JMenuItem("Guardar Tablero");
		mnGuardarTablero.setEnabled(false);
		mnIni.add(mnGuardarTablero);
		mnGuardarTablero.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Guardar.run();
			}
		});
		
		mnEstrategiasaciegas = new JMenu("Estrategias a ciegas");
		mnEstrategiasaciegas.setEnabled(false);
		menuBar.add(mnEstrategiasaciegas);
		
		mnBusqueda = new JMenuItem("Busqueda en profundidad        ");
		mnEstrategiasaciegas.add(mnBusqueda);
		
		mnEstrategiasHeuristicas = new JMenu("Estrategias heuristicas");
		mnEstrategiasHeuristicas.setEnabled(false);
		menuBar.add(mnEstrategiasHeuristicas);
		
		mnibusAstar = new JMenu("Busqueda A*                   ");
		mnEstrategiasHeuristicas.add(mnibusAstar);
		
		mntmHeuristicaCityblock = new JMenuItem("Distancia Manhattan");
		mnibusAstar.add(mntmHeuristicaCityblock);
		
		mntmHeuristicaEuclidiana = new JMenuItem("Distancia Euclidiana");
		mnibusAstar.add(mntmHeuristicaEuclidiana);
		
		mntmHeuristicaDiagonal = new JMenuItem("Distancia Diagonal");
		mnibusAstar.add(mntmHeuristicaDiagonal);
		
		mntmHeuristicaMaha = new JMenuItem("Distancia Mahalanobis");
		mnibusAstar.add(mntmHeuristicaMaha);
		
		Toolkit kit = Toolkit.getDefaultToolkit();
		
		int screenHeight = 700;
		int screenWidth = 1280;

		frame.setSize(screenWidth, screenHeight);
		frame.setLocation(screenWidth, screenHeight);
		
		Image logo = kit.getImage("./files/images/logo.png");
		frame.setIconImage(logo);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
		
		/* PANELES */
		
		JPanel panelheader; 
		panelheader = new JPanel();
		panelheader.setBorder(new MatteBorder(0, 2, 2, 5, (Color) Color.LIGHT_GRAY));
		panelheader.setBackground(Color.RED);
		
		panelTab = new JPanel();
		panelTab.setLayout(null);
		panelTab.setBackground(Color.DARK_GRAY);
		
		desktopPane = new JDesktopPane();
		desktopPane.setBackground(Color.DARK_GRAY);
		
		panelTab.add(desktopPane);
		
		desktopPane.setBounds(6, 6, 1258, 537);
		desktopPane.setBorder(UIManager.getBorder("InsetBorder.aquaVariant"));
		
		GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.TRAILING)
				.addComponent(panelheader, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 1298, GroupLayout.PREFERRED_SIZE)
				.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
					.addGap(6)
					.addComponent(panelTab, GroupLayout.PREFERRED_SIZE, 1270, GroupLayout.PREFERRED_SIZE))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addComponent(panelheader, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(panelTab, GroupLayout.PREFERRED_SIZE, 549, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(12, Short.MAX_VALUE))
		);
		
		lblTablero = new JLabel("Escenario del problema");
		lblTablero.setBounds(537, 6, 207, 21);
		lblTablero.setFont(new Font("Lucida Grande", Font.BOLD, 17));
		
		lblLeyenda = new JLabel("Leyenda:");
		lblLeyenda.setBounds(23, 48, 61, 17);
		lblLeyenda.setFont(new Font("Lucida Grande", Font.BOLD, 14));
		
		panelrobot = new JPanel();
		panelrobot.setBounds(102, 35, 28, 30);
		panelrobot.setBorder(new MatteBorder(2, 2, 2, 2, (Color) Color.LIGHT_GRAY));
		
		lblPosirobo = new JLabel("Posicion actual del robot     ");
		lblPosirobo.setBounds(142, 50, 161, 15);
		lblPosirobo.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
		
		panelobs = new JPanel();
		panelobs.setBounds(321, 35, 29, 30);
		panelobs.setBorder(new MatteBorder(2, 2, 2, 2, (Color) Color.LIGHT_GRAY));
		
		lblObstaculo = new JLabel("Obstaculo     ");
		lblObstaculo.setBounds(362, 50, 77, 15);
		lblObstaculo.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
		
		panelmeta = new JPanel();
		panelmeta.setBounds(457, 35, 30, 30);
		panelmeta.setBorder(new MatteBorder(2, 2, 2, 2, (Color) Color.LIGHT_GRAY));
		
		lblPosicionFinal = new JLabel("Posicion final ");
		lblPosicionFinal.setBounds(499, 50, 78, 15);
		lblPosicionFinal.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
		panelmeta.setLayout(new GridLayout(0, 1, 0, 0));
		
		imgfinal = new JLabel("");
		panelmeta.add(imgfinal);
		
		panelobs.setLayout(new GridLayout(0, 1, 0, 0));
		
		imgobs = new JLabel("");
		panelobs.add(imgobs);
		panelrobot.setLayout(new GridLayout(0, 1, 0, 0));
		
		imgrobot = new JLabel("");
		panelrobot.add(imgrobot);
		panelheader.setLayout(null);
		panelheader.add(lblLeyenda);
		panelheader.add(panelrobot);
		panelheader.add(lblPosirobo);
		panelheader.add(panelobs);
		panelheader.add(lblObstaculo);
		panelheader.add(panelmeta);
		panelheader.add(lblPosicionFinal);
		panelheader.add(lblTablero);
		
		JSeparator separator = new JSeparator();
		separator.setBounds(499, 23, 282, 15);
		panelheader.add(separator);
		
		btnStart = new JButton("Start");
		btnStart.setBounds(845, 15, 117, 59);
		panelheader.add(btnStart);
		
		lblNombreBoH = new JLabel("");
		lblNombreBoH.setFont(new Font("Lucida Grande", Font.BOLD, 12));
		lblNombreBoH.setBounds(974, 35, 289, 16);
		panelheader.add(lblNombreBoH);
		btnStart.setVisible(false);
		frame.getContentPane().setLayout(groupLayout);
	
		mnBusqueda.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mnEstrategiasaciegas.setEnabled(false);
				mnEstrategiasHeuristicas.setEnabled(false);
				btnStart.setVisible(true);
				opcion = 1;
				lblNombreBoH.setText("Busqueda en profundidad");
			}
		});
		
		mntmHeuristicaCityblock.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mnEstrategiasaciegas.setEnabled(false);
				mnEstrategiasHeuristicas.setEnabled(false);
				btnStart.setVisible(true);
				opcion = 2;
				tipoHeuristica = 1;
				lblNombreBoH.setText("Busqueda A* con distancia Manhattan");
			}
		});
		
		mntmHeuristicaEuclidiana.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mnEstrategiasaciegas.setEnabled(false);
				mnEstrategiasHeuristicas.setEnabled(false);
				btnStart.setVisible(true);
				opcion = 2;
				tipoHeuristica = 2;
				lblNombreBoH.setText("Busqueda A* con distancia Euclidiana");
			}
		});
		
		mntmHeuristicaDiagonal.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mnEstrategiasaciegas.setEnabled(false);
				mnEstrategiasHeuristicas.setEnabled(false);
				btnStart.setVisible(true);
				opcion = 2;
				tipoHeuristica = 3;
				lblNombreBoH.setText("Busqueda A* con distancia Diagonal");
			}
		});
		
		mntmHeuristicaMaha.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mnEstrategiasaciegas.setEnabled(false);
				mnEstrategiasHeuristicas.setEnabled(false);
				btnStart.setVisible(true);
				opcion = 2;
				tipoHeuristica = 4;
				lblNombreBoH.setText("Busqueda A* con distancia Mahalanobis");
			}
		});
		
		btnStart.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				switch (opcion) {
					case 1:
						Busqueda b = new Busqueda();
						b.lanzar_busqueda();
						break;
					case 2: 
						Busqueda_Anchura bA = new Busqueda_Anchura(tipoHeuristica);
						bA.lanza_busqueda();
						break;
					case 3:
						break;
				}
				
				btnStart.setEnabled(false);
			}
		});
	}
			

	public void visualizar() {
		frame.setVisible(true);
		imgfinal.setIcon(CargarIcono.cargarIcono("./files/images/meta.png", panelmeta.getWidth(), panelmeta.getWidth()));
		imgobs.setIcon(CargarIcono.cargarIcono("./files/images/obs.png", panelobs.getWidth(), panelobs.getWidth()));
		imgrobot.setIcon(CargarIcono.cargarIcono("./files/images/logo.png", panelrobot.getWidth(), panelrobot.getWidth()));
	}
	
	public static void MostrarCasillas() {		
		panelTablero = new JButton[Interface.getTablero().getM()][Interface.getTablero().getN()];
    	desktopPane.setLayout(new GridLayout(Interface.getTablero().getM(),Interface.getTablero().getN()));
    	
    	for (int i = 0; i < Interface.getTablero().getM(); i++) {
    		for (int j = 0; j < Interface.getTablero().getN(); j++) {
    			panelTablero[i][j] = new JButton();
    			String nombre = new Integer(i).toString() + "|";
    			nombre += new Integer(j).toString();
    			
    			panelTablero[i][j].setName(nombre);
    			desktopPane.add(panelTablero[i][j]);
    		}
    	}
    	
    	smnObs.setEnabled(false);
    	mnGuardarTablero.setEnabled(true);
		mnEstrategiasaciegas.setEnabled(true);
		mnEstrategiasHeuristicas.setEnabled(true);
    	
    	frame.validate();
    	AnadirIconoCasilla();
    	frame.repaint(); 
	}

	public static void AnadirIconoCasilla() {
		int ix = (int) getTablero().getRobot().getPosInicial().getX();
		int iy = (int) getTablero().getRobot().getPosInicial().getY();
		int fx = (int) getTablero().getRobot().getPosFinal().getX();
		int fy = (int) getTablero().getRobot().getPosFinal().getY();
		
		panelTablero[ix][iy].setIcon(CargarIcono.cargarIcono("./files/images/logo.png",
				panelTablero[ix][iy].getWidth(), panelTablero[ix][iy].getHeight()));
		panelTablero[fx][fy].setIcon(CargarIcono.cargarIcono("./files/images/meta.png",
				panelTablero[fx][fy].getWidth(), panelTablero[fx][fy].getHeight()));
		
		
		Iterator<Point> it = getTablero().getObs().iterator();
		while (it.hasNext()) {
			Point p = it.next();
			
			int ox = (int) p.getX();
			int oy = (int) p.getY();
			
			panelTablero[ox][oy].setIcon(CargarIcono.cargarIcono("./files/images/obs.png", 
					panelTablero[ox][oy].getWidth(), panelTablero[ox][oy].getHeight()));
		}
		
		frame.validate();
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == salir){
			System.exit(0);
		} else if(e.getSource() == acerca){
			Acerca_de();
			dialogo.setVisible(true);
			frame.setResizable(false);
		} else if (e.getSource() == aceptar) {
			dialogo.setVisible(false);
		} 
	}	
	
	public void Acerca_de() {
		JPanel boton = new JPanel(new FlowLayout());
	    JPanel panel1 = new JPanel(new GridLayout(4,1));
	    JPanel panel2 = new JPanel(new GridLayout(4,1));
	    
	    panel1.add(new JLabel("   Inteligencia Artificial e Ingenieria del Conocimiento   ", JLabel.CENTER));
	    panel1.add(new JLabel(""));
	    panel1.add(new JLabel(" Practica. Estrategia de Busqueda", JLabel.CENTER));
	    panel1.add(new JLabel(""));
	    panel2.add(new JLabel(" DESARROLLADO POR: ", JLabel.LEFT));
	    panel2.add(new JLabel("                                        Miguel Monterey Varela", JLabel.LEFT));
	    panel2.add(new JLabel("                                        Eduardo Perez Mederos", JLabel.LEFT));
	    panel2.add(new JLabel(""));
	    
	    boton.add(aceptar);
	    
	    dialogo = new JDialog(frame, "Acerca de IA", true);
	    dialogo.getContentPane().add(BorderLayout.NORTH, panel1);
	    dialogo.getContentPane().add(BorderLayout.CENTER ,panel2);
	    dialogo.getContentPane().add(BorderLayout.SOUTH, boton);
	    
	    dialogo.pack();
	    dialogo.setLocationRelativeTo(frame);
	}
		
	public static Tablero getTablero() {
		return Tab;
	}
}

